<template>
  <div class="init_upload"  ref="uploadRef">
    <el-upload
        v-model:file-list="files"
        class="avatar-uploader"
        :show-file-list="false"
        :multiple="true"
        :auto-upload="false"
        :on-success="test"
        :before-upload="beforeAvatarUpload"
    >
      <el-icon class="avatar-uploader-icon">
        <Plus/>
      </el-icon>
    </el-upload>
  </div>

</template>

<script setup lang="ts">
import {ElIcon, ElMessage} from "element-plus";
import {computed, nextTick, onMounted, type PropType, ref, watch} from "vue";
import {batchUploadSelf, uploadFile2} from "@/api/modules/system/upload";

let emit = defineEmits(['refreshPicture','updateUrlData'])

let files = ref()
let uploadRef = ref()

let max = ref(0)

let props = defineProps({
  masterId: {
    type: Number as PropType<number | any>,
    required: true
  },
  height: Number
});

let dynamicStyle = computed(()=>{
  let height = (80 + 22 + 290 + 120) + 'px';  // 默认高度
  let style: Record<string, string> = { minHeight: height };

  if (props.height) {
    style.minHeight = props.height+'px';
  }

  return style;
})

onMounted(()=>{
 // let target = document.querySelector(".avatar-uploader")
 //  if (target && props.height){
 //    target.style.minHeight = props.height + 'px'
 //    target.style.height = props.height + 'px'
 //  }
  if (props.height) {
    nextTick(()=>{
      let target = uploadRef.value.querySelector(".avatar-uploader")
      target.style.minHeight = props.height + 'px'
      target.style.height = props.height + 'px'
    })
  }
})

/**
 * 这里handleChange的file是逐个执行的
 * @param file
 */
// let handleChange = (uploadFile: any, uploadFiles: any) => {
//
//   console.log(uploadFile)
//   console.log('uploadFiles.length', uploadFiles.length)
//   let len = uploadFiles.length;
//   max.value = Math.max(len, uploadFiles.length);
//   setTimeout(() => {
//     if (max.value !== length) {
//       return
//     }
//     console.log('只执行了一次')
//     console.log(max.value)
//   }, 300)
//
//   // setTimeout(() => {
//   //   uploadFile2({uploadSelf: uploadFile.raw}).then(res =>{
//   //     console.log('res22222',res);
//   //     let form :DetailModePictureForm ={}
//   //     form.belongId =props.masterId
//   //     form.pictureId =res?.data
//   //     form.isAvatar = '0'
//   //     createDetailModePictureApi(form)
//   //     ElMessage.success('上传成功')
//   //     //刷新相册列表
//   //     emit('refreshPicture')
//   //   });
//   // }, 300); // 可以根据需要调整时间，确保下次触发时会重置
// }


let test = () => {
  console.log('调用了xxxx')
}


let beforeAvatarUpload = (rawFile: any) => {
  const isImage = rawFile.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片类型文件');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 100) {
    ElMessage.error('图片大小不能超过100M');
    return false;
  }
  return true;
}



//直接在这弄上传就行
let lastTime = ref(null);
watch(() => files.value, (value, oldValue) => {

    //定时检查fileList的变化，若0.5秒没有变化则触发方法
      //   lastTime.value = new Date().getTime();
      //   setTimeout(() => {
      //     let now = new Date().getTime();
      //     if (now - lastTime.value < 500) {
      //         console.log('最新的时间间隔小于500秒，不执行操作')
      //     }else {
      //         console.log('最新的时间间隔大于500秒，执行操作')
      //     }
      //     // 设置一个新的定时器，0.5秒后触发 changeImage 方法
      //     console.log('执行了方法')
      //     lastTime.value = 0
      //   },500)
      //   console.log('上传了一百个也只执行了一次测样',newValue)  对的对的
  // 确保 oldValue 是一个有效的数组，否则设为空数组
  const validOldValue = Array.isArray(oldValue) ? oldValue : [];

  // 过滤掉 oldValue 中已有的文件
  let newFiles = value.filter((s) => !validOldValue.includes(s)).map((s) => s.raw);

  batchUploadSelf({uploadSelfs: newFiles}).then(res =>{
           emit('updateUrlData',res)
        });
    }
);

defineExpose({files})

</script>


<style scoped>


.init_upload {
  position: relative;
  height: 100%; /* 确保容器高度为100% */
  width: 100%; /* 确保容器宽度为100% */
  display: flex; /* 添加 flex 布局 */
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.avatar-uploader {
  position: relative;
  width: 100%;
  min-height: calc(80px + 22px + 290px + 120px);
  display: flex; /* 使上传按钮填满容器 */
  justify-content: center; /* 居中对齐 */
  align-items: center; /* 居中对齐 */
}

.avatar-uploader .el-upload {
  width: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 100%; /* 强制 el-upload 占满父容器 */
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  position: relative;
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  min-height: calc(80px + 22px + 290px + 120px);
  text-align: center;
}


</style>